﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using BulletOnRails4NET.Controllers;
using HtmlAgilityPack;

namespace GeneCMS.Models.Helpers
{
    public class UrlHelper
    {
        public static string PATH_TO_BASE_TAG = "{path_to_base}";

        public static string PATH_TO_ROOT = "{site_root}";

        public static string AddLinkToBase(string base_url, string html)
        {
            return html.Replace(PATH_TO_BASE_TAG, GetPrefixRelativeToBase(base_url));
        }

        public static string GetPrefixRelativeToBase(string base_url)
        {
            int number_levels = base_url.Split('/').Length;
            StringBuilder path_to_base = new StringBuilder();
            for (int level_idx = 1; level_idx < number_levels; level_idx++)
            {
                path_to_base.Append("../");
            }
            return path_to_base.ToString();
        }

        public static string GetPrefixRelativeToBase(int levels_to_root)
        {
            StringBuilder path_to_base = new StringBuilder();
            for (int level_idx = 1; level_idx <= levels_to_root; level_idx++)
            {
                path_to_base.Append("../");
            }
            return path_to_base.ToString();
        }

        public static string AddPathToRoot(string html)
        {
            return html.Replace(PATH_TO_ROOT, PathResolver.GetSiteRoot());
        }

        public static HtmlDocument ConvertLinks(string base_url, string html_template_path)
        {

            HtmlDocument doc = new HtmlDocument();
            doc.Load(html_template_path);
            string prefix_relative_to_base = GetPrefixRelativeToBase(base_url);

            ConvertLinksInNodes(doc, "href", prefix_relative_to_base);
            ConvertLinksInNodes(doc, "src", prefix_relative_to_base);
            return doc;
        }

        private static void ConvertLinksInNodes(HtmlDocument doc,string attibute_to_find, string prefix_relative_to_base)
        {
            string link;
            var nodes = doc.DocumentNode.SelectNodes("//*[@" + attibute_to_find + "]");
            foreach (var node_linking in nodes)
            {
                link = node_linking.Attributes[attibute_to_find].Value;
                if (link.IndexOf(':') <= 0) //Is it a relative URL
                {
                    if (link[0] == '/')
                    {
                        link = link.Remove(0, 1); //remove the absolute path because all links in template are assume to be relative to root
                    }
                    link = prefix_relative_to_base + link;
                    node_linking.Attributes[attibute_to_find].Value = link;
                }
            }
        }
    }
}
